package com.controller;

import com.dto.HttpClientJsonResult;
import com.dto.HttpClientMapResult;
import com.dto.Login;
import com.service.iml.UserService;
import com.utils.HttpClientUtils;
import com.utils.JwtTokenUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/wx")
public class LoginController {

    @Resource
    private Login login;
    @Resource
    private UserService userService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @GetMapping("/login")
    public Map login(String code) throws Exception {
        HttpClientMapResult result = null;
        //请求微信登录接口获得微信用户唯一标识
        HttpClientJsonResult wxResult = HttpClientUtils.doGet(login.toGetRequestURL(code));
        JSONObject wxResponseJson = wxResult.getJSONObject(); //获取 JSONObject 对象
        if (!wxResponseJson.isNull(login.getOpenid())) {
            String openid = wxResponseJson.getString(login.getOpenid()); //解析id
            result = userService.login(openid);
        }
        return result != null ? result : new HttpClientMapResult().putErrMsg(wxResult);
    }

    @PostMapping("/checkLogin")
    public Map checkLogin(HttpServletRequest request) {
        boolean result = !jwtTokenUtil.isTokenExpired(request);
        return new HttpClientMapResult().setStatusCode(result ? 200 : -1).putParam("isLogin", result);
    }

}
